﻿using System;
using System.Web.Mvc;

using Hasiu.Entity;
using Hasiu.Service;
using Hasiu.Mvc.Extensions.Pager;
using Hasiu.Mvc.Filters;
using Hasiu.Mvc.Infrastructure;

namespace Hasiu.Mvc.Controllers.Admin
{
    [AdminAuthorize]
    public class NewsAdminController : Controller
    {
        public ActionResult Save(string id)
        {
            News news = null;
            if (!string.IsNullOrEmpty(id))
            {
                news = NewsService._.Get(id);
            }
            return View(news);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Save(News news, string returnUrl)
        {
            if (string.IsNullOrEmpty(news.Id))
            {
                news.Id = Guid.NewGuid().ToString("N");
                news.AddTime = DateTime.Now;
                news.ReadCount = 0;
                NewsService._.Save(news);
                return new RedirectOfAddResult("/admin/news/save.aspx");
            }
            var news2 = NewsService._.Get(news.Id);
            news2.Content = news.Content;
            news2.NewsType = news.NewsType;
            news2.Title = news.Title;
            NewsService._.Update(news2);
            return new RedirectOfUpdateResult(returnUrl);
        }

        public ActionResult Del(string id, string returnUrl)
        {
            NewsService._.Delete(id);
            return new RedirectOfDeleteResult(returnUrl);
        }

        public ActionResult List(
            int? pageIndex,
            string title,
            string newsType,
            DateTime? startTime,
            DateTime? endTime)
        {
            const int pageSize = 20;
            int dataCount;
            var list = NewsService._.GetList((pageIndex ?? 1) - 1, pageSize, out dataCount, title, newsType, startTime, endTime);
            var pagerList = new PagerList<News>(list, pageIndex ?? 1, pageSize, dataCount);
            return View(pagerList);
        }
    }
}
